package com.jsyso.weixin.utils;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;

public class HttpUtils {
	private static final HttpUtils utils = new HttpUtils();
	
	public static HttpUtils getInstance() {
		return utils;
	}
	
	private static final okhttp3.MediaType CONTENT_TYPE_FORM = okhttp3.MediaType.parse("application/x-www-form-urlencoded");
	private okhttp3.OkHttpClient httpClient;
	
	private HttpUtils() {
		// 分别设置Http的连接,写入,读取的超时时间
        httpClient = new okhttp3.OkHttpClient().newBuilder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build();
	}
	
	private String exec(okhttp3.Request request) {
        try {
            okhttp3.Response response = httpClient.newCall(request).execute();
            if (!response.isSuccessful()) throw new RuntimeException("Unexpected code " + response);
            return response.body().string();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
	
	public String get(String url) {
        okhttp3.Request request = new okhttp3.Request.Builder().url(url).get().build();
        return exec(request);
    }
	
	public String get(String url, Map<String, String> queryParas) {
        okhttp3.HttpUrl.Builder urlBuilder = okhttp3.HttpUrl.parse(url).newBuilder();
        for (Entry<String, String> entry : queryParas.entrySet()) {
            urlBuilder.addQueryParameter(entry.getKey(), entry.getValue());
        }
        okhttp3.HttpUrl httpUrl = urlBuilder.build();
        okhttp3.Request request = new okhttp3.Request.Builder().url(httpUrl).get().build();
        return exec(request);
    }
	
	public String post(String url, String params) {
        okhttp3.RequestBody body = okhttp3.RequestBody.create(CONTENT_TYPE_FORM, params);
        okhttp3.Request request = new okhttp3.Request.Builder()
            .url(url)
            .post(body)
            .build();
        return exec(request);
    }
	
	public String upload(String url, File file, String params) {
        okhttp3.RequestBody fileBody = okhttp3.RequestBody
                .create(okhttp3.MediaType.parse("application/octet-stream"), file);

        okhttp3.MultipartBody.Builder builder = new okhttp3.MultipartBody.Builder()
                .setType(okhttp3.MultipartBody.FORM)
                .addFormDataPart("media", file.getName(), fileBody);

        if (StringUtils.isNotBlank(params)) {
            builder.addFormDataPart("description", params);
        }

        okhttp3.RequestBody requestBody = builder.build();
        okhttp3.Request request = new okhttp3.Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        return exec(request);
    }
	
}
